<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '用户注册',
  },
}
</route>

<template>
  <view class="register-container">
    <!-- 标题 -->
    <text class="title">欢迎注册酒水商城用户</text>

    <!-- 注册表单 -->
    <view class="form-container">
      <wd-input
        class="input-field"
        placeholder="请输入邮箱"
        no-border
        placeholder-class="placeholder"
        v-model="email"
      />
      <view class="code-input-container">
        <wd-input
          class="input-field code-input"
          placeholder="请输入验证码"
          no-border
          placeholder-class="placeholder"
          v-model="code"
        />
        <button
          :class="['code-btn', isCounting && 'disabled']"
          @click="sendCode"
          :disabled="isCounting"
        >
          {{ codeBtnText }}
        </button>
      </view>
      <wd-input
        class="input-field"
        no-border
        show-password
        type="text"
        v-model="password"
        placeholder="设置登录密码（8-20位字符）"
      />

      <wd-input
        class="input-field"
        no-border
        show-password
        type="text"
        v-model="confirmPassword"
        placeholder="确认密码"
      />

      <!-- 协议勾选 -->
      <view class="protocol-container">
        <view
          class="checkbox-icon"
          :class="{ checked: agreeProtocol }"
          @click="agreeProtocol = !agreeProtocol"
        >
          <text v-if="agreeProtocol" class="icon-check">✓</text>
        </view>
        <text class="protocol-text">
          已阅读并同意
          <text class="link" @click="navigateToProtocol('user')">《用户协议》</text>
          和
          <text class="link" @click="navigateToProtocol('privacy')">《隐私政策》</text>
        </text>
      </view>

      <button class="register-btn" @click="handleRegister">立即注册</button>
    </view>

    <!-- 已有账号链接 -->
    <view class="footer">
      <text class="login-text" @click="navigateToLogin">已有账号？立即登录</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getEmailCode, register } from '@/service/auth/index'
import { useToast } from 'wot-design-uni'
import { validateEmail, validatePassword, validateSmsCode } from '@/utils/validate'

const toast = useToast()
const email = ref(null)
const code = ref(null)
const password = ref(null)
const confirmPassword = ref(null)
const countdown = ref(0)
const timer = ref<number | null>(null)
const agreeProtocol = ref(false)

const isCounting = computed(() => countdown.value > 0)
const codeBtnText = computed(() => (isCounting.value ? `${countdown.value}s后重发` : '获取验证码'))

// 发送验证码逻辑
const sendCode = async () => {
  if (!email.value) {
    uni.showToast({ title: '请输入邮箱', icon: 'none' })
    return
  }

  try {
    const result = await getEmailCode(email.value)
    if (result) {
      toast.success('验证码已发送')
      startCountdown()
    }
  } catch (error) {
    toast.error('验证码发送失败')
  }
}

// 倒计时逻辑
const startCountdown = () => {
  countdown.value = 60
  timer.value = setInterval(() => {
    if (countdown.value <= 0 && timer.value) {
      clearInterval(timer.value)
      return
    }
    countdown.value--
  }, 1000)
}

// 注册提交
const handleRegister = async () => {
  if (!validateForm()) return

  try {
    toast.loading('注册中...')

    const {
      data,
      code: rseCode,
      message,
    } = await register({
      email: email.value,
      smsCode: code.value,
      password: password.value,
    })
    toast.close()
    if (data && rseCode === 200) {
      toast.show('注册成功')
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    } else {
      toast.show(message || '注册失败，请稍后重试')
    }
  } catch (error) {
    toast.show('注册失败，请稍后重试')
  }
}

// 表单验证
const validateForm = () => {
  if (!agreeProtocol.value) {
    uni.showToast({ title: '请先阅读并同意协议', icon: 'none' })
    return false
  }
  const checkEmail = validateEmail(email.value)
  console.log(checkEmail)

  if (checkEmail) {
    uni.showToast({ title: checkEmail, icon: 'none' })
    return false
  }
  const checkCode = validateSmsCode(code.value)
  console.log(checkCode)
  if (checkCode) {
    uni.showToast({ title: checkCode, icon: 'none' })
    return false
  }
  const checkPwd = validatePassword(password.value)
  console.log(checkPwd)
  if (checkPwd) {
    uni.showToast({ title: checkPwd, icon: 'none' })
    return false
  }
  if (!confirmPassword.value) {
    uni.showToast({ title: '请确认密码', icon: 'none' })
  }

  if (password.value !== confirmPassword.value) {
    uni.showToast({ title: '两次输入密码不一致', icon: 'none' })
    return false
  }

  return true
}

// 协议跳转
const navigateToProtocol = (type: 'user' | 'privacy') => {
  const url = type === 'user' ? '/pages/protocol/user' : '/pages/protocol/privacy'
  uni.navigateTo({ url })
}

// 跳转登录
const navigateToLogin = () => {
  uni.navigateTo({ url: '/pages/login/index' })
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: calc(100vh - 250rpx);
  padding: 80rpx 60rpx;
  background: #ffffff;

  .title {
    display: block;
    margin-bottom: 60rpx;
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
  }

  .form-container {
    .input-field {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100rpx;
      padding: 0 30rpx;
      margin-bottom: 40rpx;
      font-size: 30rpx;
      background: #f8f8f8;
      border-radius: 12rpx;
      transition: all 0.3s;

      &:focus {
        background: #fff;
        border: 2rpx solid #ff5f15;
      }
    }

    .code-input-container {
      display: flex;
      gap: 20rpx;
      margin-bottom: 40rpx;

      .code-input {
        flex: 1;
      }

      .code-btn {
        width: 200rpx;
        height: 100rpx;
        font-size: 28rpx;
        line-height: 100rpx;
        color: white;
        text-align: center;
        background: #ff5f15;
        border-radius: 12rpx;

        &.disabled {
          cursor: not-allowed;
          background: #ccc;
        }
      }
    }

    .register-btn {
      height: 100rpx;
      margin-top: 60rpx;
      font-size: 34rpx;
      line-height: 100rpx;
      color: white;
      background: linear-gradient(90deg, #ff7900, #ff5f15);
      border-radius: 50rpx;
    }
  }

  .footer {
    margin-top: 80rpx;
    text-align: center;

    .login-text {
      color: #ff5f15;
      text-decoration: underline;
    }
  }
}

.protocol-container {
  display: flex;
  align-items: center;
  margin: 40rpx 0;
  font-size: 24rpx;
  color: #666;

  .checkbox-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
    border: 2rpx solid #ccc;
    border-radius: 6rpx;

    &.checked {
      background-color: #ff5f15;
      border-color: #ff5f15;
    }

    .icon-check {
      font-size: 24rpx;
      color: white;
      transform: translateY(-2rpx);
    }
  }

  .link {
    color: #ff5f15;
    text-decoration: none;
  }
}

.placeholder {
  color: #999;
}
</style>
